package com.example.easybuy.util;

import java.util.Date;
import java.util.UUID;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JwtUtil {
    //密钥
    public static String SECRET = "4cca0c54930b10a119710e6fa6c8210d00d9084bc46c5d3d78e34e223faf5717";
    //间隔时间(分钟)
    public static final int INTERVAL = 300;

    //生成token
    public static String createToken(String loginName){
        Date latDate=new Date();
        Date expDate=new Date(latDate.getTime()+INTERVAL*60*1000);
        return JWT.create()
                .withJWTId(UUID.randomUUID().toString())
                .withIssuedAt(latDate)
                .withExpiresAt(expDate)
                .withClaim("loginName",loginName)
                .sign(Algorithm.HMAC256(SECRET));
    }

    //根据token验证是否有效
    public static DecodedJWT verifyToken(String token){
        DecodedJWT decodedJWT=JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT;
    }

    //读取jwt中存储的数据
    public static String getLoginName(String token){
        return verifyToken(token).getClaim("loginName").asString();
    }

    public static Date getExpires(String token){
        return verifyToken(token).getExpiresAt();
    }
}
